package com.distributeredis.redis_springboot.springbooteasyexcel01.controller;

import com.alibaba.excel.EasyExcel;
import com.distributeredis.redis_springboot.springbooteasyexcel.vo.GoodsExcelDTO;
import com.distributeredis.redis_springboot.springbooteasyexcel.write.goodListener.GoodsListener;
import com.distributeredis.redis_springboot.springbooteasyexcel.write.service.GoodsService;
import com.distributeredis.redis_springboot.springbooteasyexcel01.listener.DemoDataListener;
import com.distributeredis.redis_springboot.springbooteasyexcel01.service.DemoDAO;
import com.distributeredis.redis_springboot.springbooteasyexcel01.vo.DownloadData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;

@RestController
@RequestMapping("/easyexcel")
public class DownLoadAndUploadController {
    @Autowired
    private DemoDAO demoDAO;

    @PostMapping("/download")
    public String getDownLoad(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(new ArrayList<>());
        return  "success";
    }
    /**
     * 文件excel上传
     */
    @PostMapping(value = "/upload")
    public String upload(MultipartFile file) throws Exception {
        EasyExcel.read(file.getInputStream(), DownloadData.class, new DemoDataListener(demoDAO))
                .sheet()
                .headRowNumber(3)
                .doRead();
        return "success";


    }
}
